<template>
  <div class="comment-system">
    <!-- 评论表单 -->
    <div class="comment-form">
      <el-input
          v-model="content"
          type="textarea"
          :rows="3"
          placeholder="写下你的评论..."
          resize="none"
      />
      <div class="form-actions">
        <div v-if="currentReplyId" class="reply-info">
          正在回复
          <el-button type="danger" @click="cancelReply">取消回复</el-button>
        </div>
        <el-button
            type="primary"
            @click="handleSubmit"
            :disabled="!content.trim()"
        >
          提交评论
        </el-button>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comment-list">
      <div v-for="comment in comments" :key="comment.id">
        <div class="comment-item" :style="{ marginLeft: comment.depth * 30 + 'px' }">
          <div class="comment-header">
            <img :src="comment.userAvatar" class="avatar" />
            <span class="username">{{ comment.userName }}</span>
            <span class="time">{{ comment.time }}</span>
          </div>
          <div class="comment-content">
            {{ comment.content }}
          </div>
          <div class="comment-actions">
            <el-button type="text" @click="handleReply(comment.id)">回复</el-button>
          </div>

          <!-- 递归渲染子评论 -->
          <template v-for="child in comment.children" :key="child.id">
            <div class="comment-item" :style="{ marginLeft: (child.depth || 0) * 30 + 'px' }">
              <div class="comment-header">
                <img :src="child.userAvatar" class="avatar" />
                <span class="username">{{ child.userName }}</span>
                <span class="time">{{ child.time }}</span>
              </div>
              <div class="comment-content">
                {{ child.content }}
              </div>
              <div class="comment-actions">
                <el-button type="text" @click="handleReply(child.id)">回复</el-button>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import request from '@/utils/request'
import { ElMessage } from "element-plus"
import user from "@/views/User.vue";

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
})

const props = defineProps(['writtenId'])
const emit = defineEmits(['comment-submitted'])

// 响应式数据管理
const comments = ref([])
const currentReplyId = ref(null)
const content = ref('')

// 加载评论
const loadComments = async () => {
  try {
    const res = await request.get(`/comment/selectByWrittenId/${props.writtenId}`)
/*    const res = await request.get(`/comment/selectAll`)*/
    if (res.code === '200') {
      comments.value = buildTree(res.data)
      ElMessage.success("评论加载成功")
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    ElMessage.error('评论加载失败')
  }
}

// 树形结构生成
const buildTree = (items, parentId = null, depth = 0) => {
  return items
      .filter(item => item.parentId === parentId)
      .map(item => ({
        ...item,
        depth,
        children: buildTree(items, item.id, depth + 1)
      }))
}

// 事件处理
const handleReply = (commentId) => {
  currentReplyId.value = commentId
}

const handleSubmit = async () => {
  if (!content.value.trim()) return

  try {
    await request.post('/comment/createComment', {
      writtenId: props.writtenId,
      content: content.value.trim(),
      parentId: currentReplyId.value,
      userId: data.user.id
    }).then (res => {
      if (res.code === '200') {
        ElMessage.success("评论成功")
        loadComments()
        content.value = ''
        currentReplyId.value = null
        emit('comment-submitted')
      }else{
        ElMessage.error(res.msg)
      }
    })
  } catch (error) {
    ElMessage.error('评论失败')
  }
}

const cancelReply = () => {
  currentReplyId.value = null
}

onMounted(loadComments)
</script>

<style scoped>
.comment-system {
  margin: 20px 0;
}

.comment-form {
  margin-bottom: 30px;
}

.form-actions {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.reply-info {
  color: #666;
  font-size: 14px;
}

.comment-item {
  margin: 15px 0;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  transition: all 0.3s;
}

.comment-item:hover {
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 10px;
}

.username {
  font-weight: bold;
  margin-right: 10px;
}

.time {
  color: #999;
  font-size: 12px;
}

.comment-content {
  margin: 10px 0;
  line-height: 1.6;
}

.comment-actions {
  margin-top: 10px;
}
</style>